<template>
  <van-form ref="vantForm" validate-first @submit="onSubmit" @failed="onFailed">
    <!-- list结构的form表单start -->
    <template v-for="item in formList">
      <!-- input文本框部分 -->
      <div class="filed_box" :key="item.field">
        <template
          v-if="
            [
              'text',
              'tel',
              'digit',
              'number',
              'input',
              'Number',
              'textarea',
              'password'
            ].indexOf(item.type) !== -1
          "
        >
          <van-field
            v-model.trim="searchData[item.field]"
            :required="item.required"
            :name="item.title"
            :type="item.type"
            :rows="item.rows ? item.rows : 1"
            :placeholder="
              item.placeholder ? item.placeholder : '请填写' + item.title
            "
            :readonly="item.readonly ? item.readonly : false"
            :disabled="item.disabled ? item.disabled : false"
            :rules="item.rules"
            :label="item.title"
            :right-icon="item.rightIcon"
            @click-right-icon="rightClick(item)"
            autosize
          />
        </template>
        <template v-if="['verCode'].indexOf(item.type) !== -1">
          <van-field
            v-model="searchData[item.field]"
            center
            clearable
            :label="item.title"
            :rules="item.rules"
            :name="item.title"
            :disabled="item.disabled ? item.disabled : false"
            :placeholder="
              item.placeholder ? item.placeholder : '请填写' + item.title
            "
          >
            <template #button>
              <van-button
                size="small"
                type="primary"
                :disabled="codeShow"
                @click.stop.prevent="getCode"
                >{{ codeText }}</van-button
              >
            </template>
          </van-field>
        </template>
        <!-- 开关 -->
        <template v-if="['switch'].indexOf(item.type) !== -1">
          <van-field :name="item.type" :label="item.title">
            <template #input>
              <van-switch
                size="24"
                :disabled="item.disabled ? item.disabled : false"
                v-model="searchData[item.field]"
              />
            </template>
          </van-field>
        </template>
        <!-- 计数器 -->
        <template v-if="['inputNumber'].indexOf(item.type) !== -1">
          <van-field :name="item.type" :label="item.title">
            <template #input>
              <van-stepper
                :disabled="item.disabled ? item.disabled : false"
                v-model="searchData[item.field]"
                :min="item.min"
                :max="item.max"
              />
            </template>
          </van-field>
        </template>

        <!-- 时间选择 -->
        <template
          v-if="
            [
              'date',
              'year-month',
              'month-day',
              'time',
              'datetime',
              'timePicker',
              'datehour'
            ].indexOf(item.type) !== -1
          "
        >
          <van-field
            readonly
            clickable
            :name="item.type"
            :value="searchData[item.field]"
            :disabled="item.disabled ? item.disabled : false"
            :label="item.title"
            :placeholder="item.placeholder"
            @click="
              showPicker = true;
              nowTime = item.field;
              currentDate = searchData[item.field];
            "
          />
          <van-popup
            v-model="showPicker"
            position="bottom"
            v-if="nowTime == item.field"
          >
            <van-datetime-picker
              :type="item.type"
              :min-date="minDate"
              :max-date="maxDate"
              v-model="currentDate"
              @confirm="onConfirm(item, $event)"
              @cancel="showPicker = false"
            />
          </van-popup>
        </template>
        <!-- 选择器 -->
        <template v-if="['select', 'picker'].indexOf(item.type) !== -1">
          <van-field
            readonly
            clickable
            is-link
            :disabled="item.disabled ? item.disabled : false"
            :name="item.type"
            :value="getLabel(item.options, searchData[item.field])"
            :label="item.title"
            :placeholder="
              item.placeholder ? item.placeholder : '请选择' + item.title
            "
            @click="
              showSelectPicker = true;
              nowPicker = item.field;
            "
          />
          <van-popup
            v-model="showSelectPicker"
            position="bottom"
            v-if="nowPicker == item.field && !item.disabled"
          >
            <van-picker
              show-toolbar
              round
              :columns="item.options"
              value-key="label"
              @confirm="SelectConfirm(item, $event)"
              @cancel="showSelectPicker = false"
            />
            <!-- <span class="title-2">暂无数据</span> -->
          </van-popup>
        </template>
        <!-- 头像上传 -->
        <template v-if="['uploaderImg', 'upload'].indexOf(item.type) !== -1">
          <van-field
            :name="item.type"
            :label="item.title"
            :readonly="item.readonly"
          >
            <template #input>
              <!-- <upload-com  v-on="$listeners" v-bind="$attrs" ></upload-com> -->
              <van-uploader
                v-model="searchData[item.field]"
                :disabled="item.disabled ? item.disabled : false"
                :max-count="item.maxCount"
                :before-read="beforeRead"
                :after-read="afterRead"
                @click-preview="clickPreview"
                @click.native.stop="click(item)"
              >
              </van-uploader>
            </template>
          </van-field>
        </template>
        <!-- 评分模块 -->
        <template v-if="['rate'].indexOf(item.type) !== -1">
          <van-field
            :name="item.type"
            :label="item.title"
            :disabled="item.disabled ? item.disabled : false"
          >
            <template #input>
              <van-rate v-model="searchData[item.field]" />
            </template>
          </van-field>
        </template>
        <!-- 单选框组 -->
        <template v-if="['radioGroup', 'radio'].indexOf(item.type) !== -1">
          <van-field
            :name="item.type"
            :label="item.title"
            :disabled="item.disabled ? item.disabled : false"
          >
            <template #input>
              <van-radio-group
                class="flex"
                v-model="searchData[item.field]"
                :direction="item.direction"
              >
                <van-radio
                  style="margin-right: 0.4rem"
                  v-for="(ele, indx) in item.options"
                  :key="indx"
                  :name="ele.value"
                >
                  {{ ele.label }}
                </van-radio>
              </van-radio-group>
            </template>
          </van-field>
        </template>
        <!-- 复选框组 -->
        <template
          v-if="['checkboxGroup', 'checkbox'].indexOf(item.type) !== -1"
        >
          <van-field
            :name="item.type"
            :label="item.title"
            :disabled="item.disabled ? item.disabled : false"
          >
            <template #input>
              <van-checkbox-group
                v-model="searchData[item.field]"
                :direction="item.direction"
              >
                <van-checkbox
                  v-for="(ele, indx) in item.options"
                  :key="indx"
                  :name="ele.value"
                  :shape="item.shape"
                  >{{ ele.label }}</van-checkbox
                >
              </van-checkbox-group>
            </template>
          </van-field>
        </template>
        <template v-if="['stepper'].indexOf(item.type) !== -1">
          <van-field
            :name="item.type"
            :label="item.title"
            :disabled="item.disabled ? item.disabled : false"
          >
            <template #input>
              <van-stepper v-model="searchData[item.field]" />
            </template>
          </van-field>
        </template>
      </div>
    </template>
    <!-- <div v-if="isClass === '2' " :class="['form_list_title',val.className]">
          <span>{{ val.title }}</span>
        </div>
      </div>
    </template> -->
    <div style="margin-top: 0.16rem" v-if="submitShow">
      <van-button round block type="info" native-type="submit">
        {{ btnName }}
      </van-button>
    </div>
    <slot></slot>
  </van-form>
</template>

<script>
import vue from "vue";
import vant from "vant";
import Moment from "moment";
import { ImagePreview } from "vant";
import "vant/lib/index.css";
vue.use(vant);
export default {
  name: "SeFormModel",
  props: {
    searchData: {
      type: Object,
      default: () => {}
    },
    formList: {
      type: Array,
      default: () => []
    },
    submitShow: {
      type: Boolean,
      default: () => false
    },
    btnName: {
      type: String,
      default: () => "确认"
    },
    codeShow: {
      type: Boolean,
      default: () => false
    },
    isClass: {
      type: String,
      default: () => "2"
    },
    codeText: {
      type: String,
      default: () => "获取验证码"
    }
  },
  data() {
    return {
      showPicker: false, //时间组件的显示隐藏
      showSelectPicker: false, // 选择器的显示隐藏
      propType: "",
      nowPicker: "",
      nowTime: "",
      minDate: new Date(2021, 0, 1),
      maxDate: new Date(2100, 0, 1),
      currentDate: ""
    };
  },
  mounted() {
    // this.companyList();
  },
  methods: {
    /**
     * @function onConfirm
     * @description 时间选择组件的确定赋值
     */
    onConfirm(item, time) {
      this.searchData[item.field] = Moment(time).format("YYYY-MM-DD HH:mm:ss");
      this.currentDate = this.searchData[item.field];
      console.log(this.currentDate);
      this.showPicker = false;
    },
    /**
     * @function SelectConfirm
     * @description select选择器确定赋值
     */
    SelectConfirm(item, value) {
      if (typeof value == "object") {
        //数组对象时候
        this.searchData[item.field] = value.value;
        item.value = value.value;
        this.showSelectPicker = false;
      } else {
        this.searchData[item.field] = value;
        item.value = value;
        this.showSelectPicker = false;
      }
    },
    /**
     * @function onOversize
     * @description 上传头像，显示图片的大小
     */
    onOversize(file) {
      console.log(file);
      // this.$toast('文件大小超过限制500kb')
    },
    /**
     * @function beforeRead
     * @description 上传前，显示图片格式
     */
    beforeRead(file) {
      console.log(1234);
      // accept=".png,.PNG,.jpeg,.jpg,.JPG"
      if (
        file.type !== "image/jpeg" &&
        file.type !== "image/png" &&
        file.type !== "image/jpg" &&
        file.type !== "image/gif"
      ) {
        // this.$toast('请上传 jpg,png 格式图片')
        return false;
      }
      return true;
    },
    /**
     * @function afterRead
     * @description 文件上传完完毕之后的回调
     */
    afterRead(file) {
      // file.status = 'uploading'
      // file.message = '加载...'
      this.$emit("uploadImg", [file, this.propType]);
    },
    click(item) {
      this.propType = item;
    },
    clickPreview(val) {
      console.log(val);
      ImagePreview({
        images: [val.url || item.content],
        closeable: true
      });
    },
    onSubmit(values) {
      this.$emit("submit", this.searchData);
    },
    onFailed(errorInfo) {
      console.log("failed", errorInfo);
    },
    getCode() {
      this.$emit("getCode");
    },
    rightClick(item) {
      console.log(item);
    },
    getLabel(list, value) {
      let label = "";
      if (list && list.length) {
        list.forEach(e => {
          if (typeof e == "object") {
            if (Number(e.value) == Number(value)) {
              label = e.label;
            }
          } else {
            label = value;
          }
        });
      } else {
        label = value;
      }
      return label;
    }
  }
};
</script>

<style scoped lang="scss">
.filed_box {
  border-bottom: 1px solid #f1f1f1;
}
.vant_form {
  border-radius: 0.1rem;
  overflow: hidden;
}
.van-uploader__upload {
  position: relative;
  width: 100%;
  > span {
    display: inline-block;
    width: 100%;
    height: 100%;
    > img {
      position: absolute;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      width: 30%;
      height: 50%;
    }
  }
}
::v-deep .van-uploader__input-wrapper {
  width: 100%;
}
.van-field__label {
  font-weight: 600 !important;
}
</style>
